<script setup lang="ts">
import { refreshToken, schoolCASLoginUser } from '@/api/login/userLogin';
import { useAuthStore } from '@/stores/authStore';
import { message } from 'ant-design-vue';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const VITE_BUPT_AUTH = import.meta.env.VITE_BUPT_AUTH
const authTokenStore = useAuthStore()
const router = useRouter();
const route = useRoute();
// note: 需要采用CAS协议完成统一身份登录

// note: 其他页面可以通过在 query 中传递 redirect 参数来指定登录成功后的跳转路径
const redirectPath = ref<string>(route.query.redirect as string || '/user/homepagesquare');

// 从路由中获取ticket参数
const ticket = ref<string>(route.query.ticket as string)

const successLogin = (response: any) => {
  // 设置token
  authTokenStore.setAccessToken(response.access_token)
  authTokenStore.setRefreshToken(response.refresh_token)
  // 开启定时器
  authTokenStore.startTokenRefreshTask()
  router.push({ path: redirectPath.value });
  message.success('登录成功');
}

// Attempt Auto-Login
onMounted(async () => {
  // 登录页面关闭定时刷新计时器
  // authTokenStore.stopTokenRefreshTask()
  // note: 如果是获取的ticket 那么就说明没有自动登录成功，那么不应该再指定refreshToken() 不然会反复刷新ticket。导致再统一身份登录中反复跳转
  if (ticket.value) {
    // 发送登录请求
    try {
      const response = await schoolCASLoginUser(ticket.value);
      successLogin(response)
    }
    catch (error) {
      console.error('CAS协议登录失败:', error);
      message.error(`系统原因，CAS协议登录失败`);
    }
  }
  else {
    refreshToken().then((response: any) => {
      // console.log("Auto login redirecting to:", redirectPath.value);
      // 设置token
      successLogin(response)
    }).catch((err: any) => {
      console.error('自动登录失败:', err);
      // 跳转到统一身份认证登录页面
      window.location.href = `${VITE_BUPT_AUTH}/login?service=${window.location.href}`;
    })
  }
});
</script>

<template>
  <div style="font-size: 20px;">
    ilink CAS 登录页面
  </div>
</template>
